import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import { CarController } from '../utils/carControls';
import { LightingManager } from '../utils/lightingSystem';
import { VillageGenerator } from '../utils/villageGenerator';
import { CollisionSystem } from '../utils/collisionSystem';
import { CollisionEffects } from '../utils/collisionEffects';
import { Pane } from 'tweakpane';

// 场景参数接口
interface NightSceneParams {
  showHelper: boolean;
  fogNear: number;
  fogFar: number;
  carSpeed: number;
  lightIntensity: number;
  timeOfDay: number;
  cameraMode: 'thirdPerson' | 'firstPerson' | 'overview';
  // 碰撞系统参数
  collision: {
    enabled: boolean;
    showBounds: boolean;
    showPoints: boolean;
    showNormals: boolean;
    showGrid: boolean;
    responseStrength: number;
    bounceStrength: number;
    debugMode: boolean;
  };
  // 特效系统参数
  effects: {
    enableParticles: boolean;
    enableScreenShake: boolean;
    enableFlash: boolean;
    enableSound: boolean;
    particleCount: number;
    shakeIntensity: number;
  };
}

// 夜间场景主函数
export function initNightScene(
  camera: THREE.PerspectiveCamera,
  renderer: THREE.WebGLRenderer,
  scene: THREE.Scene,
  controls: OrbitControls
): void {
  // 场景参数
  const params: NightSceneParams = {
    showHelper: false,
    fogNear: 10,
    fogFar: 50,
    carSpeed: 1.0,
    lightIntensity: 1.0,
    timeOfDay: 0.0,
    cameraMode: 'thirdPerson',
    // 碰撞系统参数
    collision: {
      enabled: true,
      showBounds: false,  // 关闭包围盒显示
      showPoints: true,
      showNormals: true,
      showGrid: false,
      responseStrength: 1.0,
      bounceStrength: 0.3,
      debugMode: false   // 关闭调试模式
    },
    // 特效系统参数
    effects: {
      enableParticles: true,
      enableScreenShake: false,  // 默认关闭震动效果以防止闪烁
      enableFlash: true,
      enableSound: false,
      particleCount: 20,
      shakeIntensity: 0.1
    }
  };

  // 时钟和渲染器设置
  const clock = new THREE.Clock();
  renderer.shadowMap.enabled = true;
  renderer.shadowMap.type = THREE.PCFSoftShadowMap;
  renderer.setClearColor(0x111133);

  // 添加雾效
  scene.fog = new THREE.Fog(0x111133, params.fogNear, params.fogFar);

  // 创建车辆模型
  const carGroup = createCarModel();
  scene.add(carGroup);

  // 初始化系统
  const villageGenerator = new VillageGenerator(scene);
  const lightingManager = new LightingManager(scene);
  const carController = new CarController(carGroup);
  
  // 初始化特效系统
  const collisionEffects = new CollisionEffects(scene, camera, {
    enableParticles: params.effects.enableParticles,
    enableScreenShake: params.effects.enableScreenShake,
    enableFlash: params.effects.enableFlash,
    enableSound: params.effects.enableSound,
    particleCount: params.effects.particleCount,
    shakeIntensity: params.effects.shakeIntensity
  });
  
  // 初始化碰撞系统
  const collisionSystem = new CollisionSystem(scene, {
    enableCollision: params.collision.enabled,
    showBoundingBoxes: params.collision.showBounds,
    showCollisionPoints: params.collision.showPoints,
    showCollisionNormals: params.collision.showNormals,
    showSpatialGrid: params.collision.showGrid,
    responseStrength: params.collision.responseStrength,
    bounceStrength: params.collision.bounceStrength,
    debugMode: params.collision.debugMode,
    gridSize: 10
  }, {
    onCollisionStart: (collisions) => {
      console.log(`碰撞开始！检测到 ${collisions.length} 个碰撞`);
      console.log('碰撞详情:', collisions);
      // 触发碰撞特效
      collisionEffects.triggerCollisionEffects(collisions);
    },
    onCollisionEnd: () => {
      console.log('碰撞结束');
    },
    onCollisionUpdate: (collisions, response) => {
      if (response.positionCorrected || response.velocityAdjusted) {
        console.log(`碰撞响应：位置修正=${response.positionCorrected}, 速度调整=${response.velocityAdjusted}`);
      }
    }
  });

  // 生成村庄
  villageGenerator.generateVillage();

  // 为建筑物和树木添加窗户灯光并注册到碰撞系统
  addBuildingLights(villageGenerator, lightingManager, collisionSystem);

  // 设置车灯切换回调
  carController.onLightToggle = () => {
    lightingManager.getCarLighting().toggleLights();
  };

  // 启动窗户闪烁效果
  lightingManager.getEnvironmentLighting().startFlickerEffect();

  // 相机设置
  let cameraOffset = new THREE.Vector3(0, 8, -15);
  let cameraTarget = new THREE.Vector3();

  // 调试面板
  const pane = new Pane({ title: '夜间村庄控制面板' });
  setupDebugPanel(pane, params, scene, lightingManager, carController, collisionSystem, collisionEffects);

  // 渲染循环
  function animate(): void {
    const deltaTime = clock.getDelta();

    // 更新车辆
    carController.update(deltaTime);
    const carState = carController.getCarState();

    // 更新碰撞检测和响应
    const { collisions, response } = collisionSystem.update(carGroup, carController, deltaTime);
    
    // 显示碰撞检测调试信息（每秒一次）
    const currentTime = Date.now();
    if (currentTime - (window as any).lastCollisionDebugTime > 1000) {
      (window as any).lastCollisionDebugTime = currentTime;
      
      console.log('=== 碰撞检测状态 ===');
      console.log('车辆位置:', carGroup.position);
      console.log('注册的建筑物数量:', collisionSystem.getBuildingCount());
      console.log('当前碰撞数量:', collisions.length);
      
      if (collisions.length > 0) {
        console.log('检测到碰撞:', collisions);
        console.log('碰撞响应:', response);
      }
    }

    // 更新特效系统
    collisionEffects.update(deltaTime);

    // 更新车灯位置
    const lightPositions = carController.getLightPositions();
    const frontDirection = carController.getFrontDirection();
    
    lightingManager.getCarLighting().updateLights(
      lightPositions.frontLeft,
      lightPositions.frontRight,
      lightPositions.rearLeft,
      lightPositions.rearRight,
      frontDirection,
      carState.isBreaking
    );

    // 更新相机（带震动效果）
    const shakeOffset = collisionEffects.getShakeOffset();
    updateCamera(camera, controls, carGroup, params.cameraMode, cameraOffset, cameraTarget, shakeOffset);

    // 更新环境光照（模拟时间变化）
    lightingManager.getEnvironmentLighting().adjustTimeOfDay(params.timeOfDay);

    // 渲染场景
    renderer.render(scene, camera);
    requestAnimationFrame(animate);
  }

  animate();

  // 清理函数
  window.addEventListener('beforeunload', () => {
    carController.dispose();
    lightingManager.dispose();
    villageGenerator.dispose();
    collisionSystem.dispose();
    collisionEffects.dispose();
    pane.dispose();
  });
}

// 创建车辆模型
function createCarModel(): THREE.Group {
  const carGroup = new THREE.Group();

  // 车身
  const bodyGeometry = new THREE.BoxGeometry(2, 1, 4);
  const bodyMaterial = new THREE.MeshStandardMaterial({
    color: 0x4a4a4a,
    metalness: 0.8,
    roughness: 0.2
  });
  const carBody = new THREE.Mesh(bodyGeometry, bodyMaterial);
  carBody.position.y = 0.5;
  carBody.castShadow = true;
  carBody.receiveShadow = true;
  carGroup.add(carBody);

  // 车轮
  const wheelGeometry = new THREE.CylinderGeometry(0.4, 0.4, 0.3, 12);
  const wheelMaterial = new THREE.MeshStandardMaterial({
    color: 0x333333,
    metalness: 0.9,
    roughness: 0.1
  });

  const wheelPositions = [
    { x: 0.9, y: 0.4, z: 1.2 },   // 前右
    { x: -0.9, y: 0.4, z: 1.2 },  // 前左
    { x: 0.9, y: 0.4, z: -1.2 },  // 后右
    { x: -0.9, y: 0.4, z: -1.2 }  // 后左
  ];

  wheelPositions.forEach(pos => {
    const wheel = new THREE.Mesh(wheelGeometry, wheelMaterial);
    wheel.position.set(pos.x, pos.y, pos.z);
    wheel.rotation.z = Math.PI / 2;
    wheel.castShadow = true;
    carGroup.add(wheel);
  });

  // 车前灯罩
  const headlightGeometry = new THREE.SphereGeometry(0.15, 8, 8);
  const headlightMaterial = new THREE.MeshStandardMaterial({
    color: 0xffffff,
    transparent: true,
    opacity: 0.8,
    emissive: 0x444444
  });

  const leftHeadlight = new THREE.Mesh(headlightGeometry, headlightMaterial);
  leftHeadlight.position.set(-0.6, 0.7, 1.8);
  carGroup.add(leftHeadlight);

  const rightHeadlight = new THREE.Mesh(headlightGeometry, headlightMaterial);
  rightHeadlight.position.set(0.6, 0.7, 1.8);
  carGroup.add(rightHeadlight);

  // 车尾灯
  const taillightGeometry = new THREE.SphereGeometry(0.1, 8, 8);
  const taillightMaterial = new THREE.MeshStandardMaterial({
    color: 0xff0000,
    emissive: 0x440000,
    emissiveIntensity: 0.5
  });

  const leftTaillight = new THREE.Mesh(taillightGeometry, taillightMaterial);
  leftTaillight.position.set(-0.6, 0.7, -1.8);
  carGroup.add(leftTaillight);

  const rightTaillight = new THREE.Mesh(taillightGeometry, taillightMaterial);
  rightTaillight.position.set(0.6, 0.7, -1.8);
  carGroup.add(rightTaillight);

  // 车窗
  const windowGeometry = new THREE.BoxGeometry(1.6, 0.8, 2);
  const windowMaterial = new THREE.MeshStandardMaterial({
    color: 0x222222,
    transparent: true,
    opacity: 0.7,
    metalness: 0.1,
    roughness: 0.1
  });
  const carWindow = new THREE.Mesh(windowGeometry, windowMaterial);
  carWindow.position.y = 1.2;
  carGroup.add(carWindow);

  return carGroup;
}

// 为建筑物添加窗户灯光并注册到碰撞系统
function addBuildingLights(
  villageGenerator: VillageGenerator, 
  lightingManager: LightingManager,
  collisionSystem: CollisionSystem
): void {
  const buildings = villageGenerator.getBuildings();
  const vegetation = villageGenerator.getVegetation();
  
  console.log('=== 碰撞系统注册开始 ===');
  console.log(`找到 ${buildings.length} 个建筑物，开始注册到碰撞系统`);
  console.log(`找到 ${vegetation.length} 个植被对象（树木），开始注册到碰撞系统`);
  
  // 注册建筑物到碰撞系统
  buildings.forEach((building, index) => {
    console.log(`正在注册建筑物 ${index + 1}/${buildings.length}:`, {
      position: building.position,
      scale: building.scale,
      rotation: building.rotation.y
    });
    
    try {
      collisionSystem.addBuilding(building);
      console.log(`✓ 建筑物 ${index + 1} 注册成功`);
    } catch (error) {
      console.error(`✗ 建筑物 ${index + 1} 注册失败:`, error);
    }
    
    // 为每个建筑物添加随机的窗户灯光
    const lightCount = Math.floor(Math.random() * 3) + 1;
    
    for (let i = 0; i < lightCount; i++) {
      const lightPosition = new THREE.Vector3(
        building.position.x + (Math.random() - 0.5) * 4,
        Math.random() * 2 + 1,
        building.position.z + (Math.random() - 0.5) * 4
      );
      
      const colors = [0xffaa44, 0x44aaff, 0xaa44ff, 0x44ff88];
      const color = colors[Math.floor(Math.random() * colors.length)];
      
      lightingManager.getEnvironmentLighting().addVillageLight(
        lightPosition,
        color,
        Math.random() * 0.4 + 0.2
      );
    }
  });
  
  // 注册树木到碰撞系统
  vegetation.forEach((tree, index) => {
    console.log(`正在注册树木 ${index + 1}/${vegetation.length}:`, {
      position: tree.position,
      scale: tree.scale,
      rotation: tree.rotation.y
    });
    
    try {
      collisionSystem.addBuilding(tree); // 树木作为静态障碍物
      console.log(`✓ 树木 ${index + 1} 注册成功`);
    } catch (error) {
      console.error(`✗ 树木 ${index + 1} 注册失败:`, error);
    }
  });
  
  // 显示最终注册统计
  const totalRegistered = collisionSystem.getBuildingCount();
  console.log(`=== 碰撞系统注册完成 ===`);
  console.log(`总计注册对象数量: ${totalRegistered}`);
  console.log(`预期注册数量: ${buildings.length + vegetation.length}`);
  
  if (totalRegistered !== buildings.length + vegetation.length) {
    console.warn('⚠️ 注册数量不匹配，可能存在问题！');
  } else {
    console.log('✅ 所有对象注册成功！');
  }
}

// 更新相机
function updateCamera(
  camera: THREE.PerspectiveCamera,
  controls: OrbitControls,
  carGroup: THREE.Group,
  cameraMode: string,
  offset: THREE.Vector3,
  target: THREE.Vector3,
  shakeOffset: THREE.Vector3 = new THREE.Vector3()
): void {
  const carPosition = carGroup.position;
  const carRotation = carGroup.rotation.y;

  switch (cameraMode) {
    case 'thirdPerson':
      // 第三人称视角：跟随车辆
      controls.enabled = false;
      
      // 计算相机位置（车辆后方）
      const thirdPersonOffset = offset.clone().applyAxisAngle(new THREE.Vector3(0, 1, 0), carRotation);
      camera.position.copy(carPosition).add(thirdPersonOffset).add(shakeOffset);
      
      // 看向车辆前方
      const frontDirection = new THREE.Vector3(0, 0, 1).applyAxisAngle(new THREE.Vector3(0, 1, 0), carRotation);
      target.copy(carPosition).add(frontDirection.multiplyScalar(10));
      camera.lookAt(target);
      break;

    case 'firstPerson':
      // 第一人称视角：驾驶舱内
      controls.enabled = false;
      const firstPersonOffset = new THREE.Vector3(0, 1.5, 0.5).applyAxisAngle(new THREE.Vector3(0, 1, 0), carRotation);
      camera.position.copy(carPosition).add(firstPersonOffset).add(shakeOffset);
      
      const drivingDirection = new THREE.Vector3(0, 0, 1).applyAxisAngle(new THREE.Vector3(0, 1, 0), carRotation);
      target.copy(carPosition).add(drivingDirection.multiplyScalar(20));
      camera.lookAt(target);
      break;

    case 'overview':
      // 俯视视角：自由控制
      controls.enabled = true;
      controls.target.copy(carPosition);
      controls.update();
      break;
  }
}

// 设置调试面板
function setupDebugPanel(
  pane: Pane,
  params: NightSceneParams,
  scene: THREE.Scene,
  lightingManager: LightingManager,
  carController: CarController,
  collisionSystem: CollisionSystem,
  collisionEffects: CollisionEffects
): void {
  // 场景控制文件夹
  const sceneFolder = pane.addFolder({ title: '场景设置' });
  
  sceneFolder.addBinding(params, 'showHelper', { label: '显示辅助线' })
    .on('change', ({ value }) => {
      if (value) {
        const axesHelper = new THREE.AxesHelper(10);
        axesHelper.name = 'axesHelper';
        scene.add(axesHelper);
      } else {
        const helper = scene.getObjectByName('axesHelper');
        if (helper) scene.remove(helper);
      }
    });

  sceneFolder.addBinding(params, 'fogNear', { 
    min: 5, 
    max: 30, 
    step: 1, 
    label: '雾效近距离' 
  }).on('change', ({ value }) => {
    if (scene.fog && scene.fog instanceof THREE.Fog) {
      scene.fog.near = value;
    }
  });

  sceneFolder.addBinding(params, 'fogFar', { 
    min: 30, 
    max: 100, 
    step: 1, 
    label: '雾效远距离' 
  }).on('change', ({ value }) => {
    if (scene.fog && scene.fog instanceof THREE.Fog) {
      scene.fog.far = value;
    }
  });

  sceneFolder.addBinding(params, 'timeOfDay', { 
    min: 0, 
    max: 1, 
    step: 0.01, 
    label: '时间（0=深夜，1=黎明）' 
  });

  // 车辆控制文件夹
  const carFolder = pane.addFolder({ title: '车辆设置' });
  
  carFolder.addBinding(params, 'carSpeed', { 
    min: 0.1, 
    max: 3, 
    step: 0.1, 
    label: '车辆速度倍率' 
  }).on('change', ({ value }) => {
    const carState = carController.getCarState();
    carState.maxSpeed = 8 * value;
  });

  carFolder.addBinding(params, 'cameraMode', {
    options: {
      '第三人称': 'thirdPerson',
      '第一人称': 'firstPerson',
      '俯视': 'overview'
    },
    label: '相机模式'
  });

  // 灯光控制文件夹
  const lightFolder = pane.addFolder({ title: '灯光设置' });
  
  lightFolder.addBinding(params, 'lightIntensity', { 
    min: 0, 
    max: 30, 
    step: 0.1, 
    label: '车灯强度' 
  }).on('change', ({ value }) => {
    lightingManager.getCarLighting().setIntensity(2.0 * value, 0.5 * value);
  });

  lightFolder.addButton({ title: '切换车灯' })
    .on('click', () => {
      lightingManager.getCarLighting().toggleLights();
    });

  // 碰撞系统控制文件夹
  const collisionFolder = pane.addFolder({ title: '碰撞检测' });
  
  collisionFolder.addBinding(params.collision, 'enabled', { 
    label: '启用碰撞检测' 
  }).on('change', ({ value }) => {
    collisionSystem.setEnabled(value);
  });
  
  collisionFolder.addBinding(params.collision, 'debugMode', { 
    label: '调试模式' 
  }).on('change', ({ value }) => {
    collisionSystem.setDebugMode(value);
  });
  
  collisionFolder.addBinding(params.collision, 'showBounds', { 
    label: '显示边界框' 
  }).on('change', ({ value }) => {
    collisionSystem.setShowBoundingBoxes(value);
  });
  
  collisionFolder.addBinding(params.collision, 'showPoints', { 
    label: '显示碰撞点' 
  }).on('change', ({ value }) => {
    collisionSystem.setShowCollisionPoints(value);
  });
  
  collisionFolder.addBinding(params.collision, 'showNormals', { 
    label: '显示法向量' 
  }).on('change', ({ value }) => {
    collisionSystem.setShowCollisionNormals(value);
  });
  
  collisionFolder.addBinding(params.collision, 'showGrid', { 
    label: '显示空间网格' 
  }).on('change', ({ value }) => {
    collisionSystem.setShowSpatialGrid(value);
  });
  
  collisionFolder.addBinding(params.collision, 'responseStrength', { 
    min: 0, 
    max: 2, 
    step: 0.1, 
    label: '响应强度' 
  }).on('change', ({ value }) => {
    collisionSystem.setResponseStrength(value);
  });
  
  collisionFolder.addBinding(params.collision, 'bounceStrength', { 
    min: 0, 
    max: 1, 
    step: 0.1, 
    label: '弹性强度' 
  }).on('change', ({ value }) => {
    collisionSystem.setBounceStrength(value);
  });
  
  // 碰撞统计信息
  const collisionStats = collisionSystem.getStats();
  
  collisionFolder.addBinding(collisionStats, 'totalCollisions', {
    readonly: true,
    label: '总碰撞次数'
  });
  
  collisionFolder.addBinding(collisionStats, 'currentCollisions', {
    readonly: true,
    label: '当前碰撞数'
  });
  
  collisionFolder.addButton({ title: '重置统计' })
    .on('click', () => {
      collisionSystem.resetStats();
    });
    
  // 添加调试按钮
  collisionFolder.addButton({ title: '打印系统信息' }).on('click', () => {
    console.log('=== 碰撞系统调试信息 ===');
    console.log('建筑物数量:', collisionSystem.getBuildingCount());
    console.log('系统启用状态:', collisionSystem.isEnabled());
    console.log('车辆位置:', carGroup.position);
    console.log('系统配置:', collisionSystem.getConfig());
    console.log('统计信息:', collisionSystem.getStats());
  });
  
  collisionFolder.addButton({ title: '测试碰撞检测' }).on('click', () => {
    console.log('=== 手动测试碰撞检测 ===');
    const carState = carController.getCarState();
    const { collisions, response } = collisionSystem.update(carGroup, carController, 0.016);
    console.log('检测结果:', {
      车辆位置: carGroup.position,
      碰撞数量: collisions.length,
      碰撞详情: collisions,
      响应结果: response
    });
  });

  // 特效系统控制文件夹
  const effectsFolder = pane.addFolder({ title: '碰撞特效' });
  
  effectsFolder.addBinding(params.effects, 'enableParticles', { 
    label: '粒子特效' 
  }).on('change', ({ value }) => {
    collisionEffects.updateConfig({ enableParticles: value });
  });
  
  effectsFolder.addBinding(params.effects, 'enableScreenShake', { 
    label: '屏幕震动' 
  }).on('change', ({ value }) => {
    collisionEffects.updateConfig({ enableScreenShake: value });
  });
  
  effectsFolder.addBinding(params.effects, 'enableFlash', { 
    label: '闪光特效' 
  }).on('change', ({ value }) => {
    collisionEffects.updateConfig({ enableFlash: value });
  });
  
  effectsFolder.addBinding(params.effects, 'enableSound', { 
    label: '碰撞音效' 
  }).on('change', ({ value }) => {
    collisionEffects.updateConfig({ enableSound: value });
  });
  
  effectsFolder.addBinding(params.effects, 'particleCount', { 
    min: 5, 
    max: 50, 
    step: 1, 
    label: '粒子数量' 
  }).on('change', ({ value }) => {
    collisionEffects.updateConfig({ particleCount: value });
  });
  
  effectsFolder.addBinding(params.effects, 'shakeIntensity', { 
    min: 0, 
    max: 0.5, 
    step: 0.01, 
    label: '震动强度' 
  }).on('change', ({ value }) => {
    collisionEffects.updateConfig({ shakeIntensity: value });
  });

  // 操作说明文件夹
  const controlsFolder = pane.addFolder({ title: '操作说明' });
  const controlsText = {
    info: 'WASD: 移动车辆\n鼠标: 调整视角\nL: 开关车灯\n空格: 刹车'
  };
  
  controlsFolder.addBinding(controlsText, 'info', {
    readonly: true,
    multiline: true,
    rows: 4,
    label: '控制键'
  });

  // 性能监控文件夹
  const performanceFolder = pane.addFolder({ title: '性能监控' });
  const fpsMonitor = { fps: 0 };
  
  performanceFolder.addBinding(fpsMonitor, 'fps', {
    readonly: true,
    label: 'FPS'
  });

  // FPS 计算
  let lastTime = performance.now();
  let frameCount = 0;
  
  const updateFPS = () => {
    frameCount++;
    const currentTime = performance.now();
    
    if (currentTime - lastTime >= 1000) {
      fpsMonitor.fps = Math.round((frameCount * 1000) / (currentTime - lastTime));
      frameCount = 0;
      lastTime = currentTime;
    }
    
    requestAnimationFrame(updateFPS);
  };
  
  updateFPS();
}
